package eu.telecom_bretagne.RECRUT.servlet;

import java.io.IOException;
import java.sql.Date;
import java.util.GregorianCalendar;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import eu.telecom_bretagne.RECRUT.service.IServiceEntretien;

/**
 * Servlet implementation class CreatiobEntretien
 */
@WebServlet("/creer_entretien")
public class CreationEntretien extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CreationEntretien() {
        super();
    }

	public final static Date convertNumericToDate(Integer dateNumeric) {
		GregorianCalendar calendar = new GregorianCalendar();
		Date date = null;
		// Si la date est au bon format
		if (dateNumeric != null && dateNumeric != 0
				&& dateNumeric.toString().length() == 8) {
			String dateString = dateNumeric.toString();
			calendar.clear();
			calendar.set(Integer.parseInt(dateString.substring(0, 4)),
					Integer.parseInt(dateString.substring(4, 6)),
					Integer.parseInt(dateString.substring(6, 8)));
			date = new Date(calendar.getTimeInMillis());
		}
		return date;
	}
    
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String idT = request.getParameter("date");
		String idD = request.getParameter("dossier");

		try {
			int idDossier = Integer.parseInt(idD);
			int date = Integer.parseInt(idT);
			InitialContext ctx = new InitialContext();
			IServiceEntretien serviceEntretien = (IServiceEntretien) ctx
					.lookup(IServiceEntretien.JNDI_NAME);
			serviceEntretien.creerEntretien(convertNumericToDate(date), idDossier);
		} catch (NamingException e) {
			throw new ServletException(e);
		}
		response.sendRedirect("index.jsp");
	}

}
